<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SQLite数据库浏览器 - 修复版</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: #333;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .container {
            width: 100%;
            max-width: 1200px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            margin: 20px;
        }
        
        header {
            background: #2575fc;
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        h1 {
            font-size: 2.2rem;
            margin-bottom: 10px;
        }
        
        .description {
            font-size: 1.1rem;
            opacity: 0.9;
            max-width: 800px;
            margin: 0 auto;
        }
        
        .upload-section {
            padding: 30px;
            text-align: center;
            border-bottom: 1px solid #eee;
        }
        
        .file-input {
            display: none;
        }
        
        .file-label {
            display: inline-block;
            padding: 15px 30px;
            background: #6a11cb;
            color: white;
            border-radius: 50px;
            cursor: pointer;
            font-size: 1.1rem;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(106, 17, 203, 0.3);
        }
        
        .file-label:hover {
            background: #5a0db9;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(106, 17, 203, 0.4);
        }
        
        .file-info {
            margin-top: 15px;
            font-size: 1rem;
            color: #666;
        }
        
        .content-section {
            display: flex;
            flex-direction: row;
            height: 500px;
        }
        
        .tables-panel {
            width: 250px;
            border-right: 1px solid #eee;
            padding: 20px;
            overflow-y: auto;
        }
        
        .tables-panel h2 {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: #2575fc;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }
        
        .table-list {
            list-style: none;
        }
        
        .table-item {
            padding: 12px 15px;
            margin-bottom: 8px;
            background: #f8f9fa;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .table-item:hover {
            background: #e9ecef;
        }
        
        .table-item.active {
            background: #2575fc;
            color: white;
        }
        
        .data-panel {
            flex: 1;
            padding: 20px;
            overflow: auto;
        }
        
        .data-panel h2 {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: #2575fc;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            font-size: 0.9rem;
        }
        
        th, td {
            padding: 10px 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #495057;
            position: sticky;
            top: 0;
        }
        
        tr:hover {
            background-color: #f1f3f5;
        }
        
        .status {
            padding: 20px;
            text-align: center;
            color: #666;
            font-style: italic;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: white;
            margin-top: auto;
        }
        
        .error {
            color: #dc3545;
            background: #f8d7da;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
        }
        
        .sample-db {
            margin-top: 15px;
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .sample-db a {
            color: #6a11cb;
            text-decoration: none;
        }
        
        .sample-db a:hover {
            text-decoration: underline;
        }
        
        @media (max-width: 768px) {
            .content-section {
                flex-direction: column;
                height: auto;
            }
            
            .tables-panel {
                width: 100%;
                border-right: none;
                border-bottom: 1px solid #eee;
                max-height: 200px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>SQLite数据库浏览器 - 修复版</h1>
            <p class="description">上传SQLite数据库文件(.db/.sqlite/.sqlite3)并在浏览器中查看其内容</p>
        </header>
        
        <div class="upload-section">
            <input type="file" id="db-file" class="file-input" accept=".db,.sqlite,.sqlite3">
            <label for="db-file" class="file-label">选择数据库文件</label>
            <p class="file-info" id="file-info">尚未选择文件</p>
            
            <div class="sample-db">
                <p>没有SQLite数据库文件？<a href="#" id="create-sample">创建示例数据库</a></p>
            </div>
        </div>
        
        <div class="content-section">
            <div class="tables-panel">
                <h2>数据表</h2>
                <ul class="table-list" id="table-list">
                    <li class="table-item">上传数据库后显示表列表</li>
                </ul>
            </div>
            
            <div class="data-panel">
                <h2>数据内容</h2>
                <div id="table-data">请从左侧选择数据表</div>
            </div>
        </div>
        
        <div class="status" id="status">
            等待上传数据库文件...
        </div>
    </div>
    
    <div class="footer">
        <p>SQLite数据库浏览器 &copy; 2023 - 修复版</p>
    </div>

    <!-- 引入sql.js库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>
    <script>
        // 初始化变量
        let db = null;
        const fileInput = document.getElementById('db-file');
        const fileInfo = document.getElementById('file-info');
        const tableList = document.getElementById('table-list');
        const tableData = document.getElementById('table-data');
        const status = document.getElementById('status');
        const createSampleBtn = document.getElementById('create-sample');
        
        // 加载SQL.js
        status.textContent = '正在加载SQL.js引擎...';
        
        // 配置SQL.js
        const config = {
            locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}`
        };
        
        // 初始化数据库
        initSqlJs(config).then(function(SQL) {
            status.textContent = 'SQL.js引擎加载完成，请上传数据库文件';
            
            // 文件选择事件处理
            fileInput.addEventListener('change', function(event) {
                const file = event.target.files[0];
                if (!file) return;
                
                fileInfo.textContent = `已选择: ${file.name} (${(file.size / 1024).toFixed(2)} KB)`;
                status.textContent = '正在读取数据库...';
                
                const reader = new FileReader();
                reader.onload = function() {
                    try {
                        // 解析数据库文件
                        const Uints = new Uint8Array(reader.result);
                        db = new SQL.Database(Uints);
                        
                        // 显示数据库表
                        displayTables();
                        status.textContent = '数据库加载成功！';
                    } catch (error) {
                        console.error(error);
                        status.textContent = '错误: ' + error.message;
                        tableData.innerHTML = '<div class="error">无法解析数据库文件，请确保是有效的SQLite数据库</div>';
                    }
                };
                reader.onerror = function() {
                    status.textContent = '读取文件时发生错误';
                    tableData.innerHTML = '<div class="error">读取文件时发生错误，请重试</div>';
                };
                reader.readAsArrayBuffer(file);
            });
            
            // 创建示例数据库
            createSampleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                createSampleDatabase(SQL);
            });
            
        }).catch(function(error) {
            status.textContent = '加载SQL.js失败: ' + error.message;
            console.error(error);
            tableData.innerHTML = '<div class="error">加载SQL.js引擎失败: ' + error.message + '</div>';
        });
        
        // 创建示例数据库
        function createSampleDatabase(SQL) {
            try {
                status.textContent = '正在创建示例数据库...';
                
                // 创建新的内存数据库
                db = new SQL.Database();
                
                // 创建示例表和数据
                db.run(`
                    CREATE TABLE users (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        name TEXT NOT NULL,
                        email TEXT NOT NULL,
                        age INTEGER,
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
                    );
                `);
                
                db.run(`
                    CREATE TABLE products (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        name TEXT NOT NULL,
                        price REAL NOT NULL,
                        category TEXT,
                        in_stock BOOLEAN DEFAULT 1
                    );
                `);
                
                // 插入示例数据
                db.run(`
                    INSERT INTO users (name, email, age) VALUES
                    ('张三', 'zhangsan@example.com', 28),
                    ('李四', 'lisi@example.com', 32),
                    ('王五', 'wangwu@example.com', 25),
                    ('赵六', 'zhaoliu@example.com', 45);
                `);
                
                db.run(`
                    INSERT INTO products (name, price, category) VALUES
                    ('笔记本电脑', 5999.99, '电子产品'),
                    ('智能手机', 3999.50, '电子产品'),
                    ('办公椅', 899.00, '家具'),
                    ('咖啡机', 1250.00, '家电'),
                    ('书籍', 59.99, '文化用品');
                `);
                
                fileInfo.textContent = '使用示例数据库';
                displayTables();
                status.textContent = '示例数据库创建成功！';
                
            } catch (error) {
                console.error(error);
                status.textContent = '创建示例数据库时出错: ' + error.message;
                tableData.innerHTML = '<div class="error">创建示例数据库时出错: ' + error.message + '</div>';
            }
        }
        
        // 显示数据库中的所有表
        function displayTables() {
            try {
                // 获取所有表名
                const tables = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
                
                if (!tables || tables.length === 0) {
                    tableList.innerHTML = '<li class="table-item">数据库中没有找到表</li>';
                    return;
                }
                
                // 清空表列表
                tableList.innerHTML = '';
                
                // 添加表到列表
                tables[0].values.forEach(tableNameArray => {
                    const tableName = tableNameArray[0];
                    const li = document.createElement('li');
                    li.className = 'table-item';
                    li.textContent = tableName;
                    li.addEventListener('click', function() {
                        // 移除所有active类
                        document.querySelectorAll('.table-item').forEach(item => {
                            item.classList.remove('active');
                        });
                        // 添加active类到当前项
                        li.classList.add('active');
                        // 显示表数据
                        displayTableData(tableName);
                    });
                    tableList.appendChild(li);
                });
                
                // 默认选择第一个表
                if (tables[0].values.length > 0) {
                    const firstTable = tables[0].values[0][0];
                    const firstTableItem = tableList.querySelector('.table-item');
                    if (firstTableItem) {
                        firstTableItem.classList.add('active');
                        displayTableData(firstTable);
                    }
                }
            } catch (error) {
                console.error(error);
                status.textContent = '获取表列表时出错: ' + error.message;
                tableData.innerHTML = '<div class="error">获取表列表时出错: ' + error.message + '</div>';
            }
        }
        
        // 显示表数据
        function displayTableData(tableName) {
            status.textContent = `正在加载表: ${tableName}`;
            
            try {
                // 查询表数据
                const result = db.exec(`SELECT * FROM ${tableName}`);
                
                if (!result || result.length === 0) {
                    tableData.innerHTML = '<p>表中没有数据</p>';
                    status.textContent = `表 "${tableName}" 中没有数据`;
                    return;
                }
                
                const columns = result[0].columns;
                const values = result[0].values;
                
                // 创建表格
                let html = '<table>';
                
                // 表头
                html += '<tr>';
                columns.forEach(col => {
                    html += `<th>${col}</th>`;
                });
                html += '</tr>';
                
                // 表数据
                values.forEach(row => {
                    html += '<tr>';
                    row.forEach(cell => {
                        // 处理NULL值和长文本
                        let cellContent = cell;
                        if (cell === null) {
                            cellContent = '<i>NULL</i>';
                        } else if (typeof cell === 'string' && cell.length > 50) {
                            cellContent = cell.substring(0, 50) + '...';
                        }
                        html += `<td>${cellContent}</td>`;
                    });
                    html += '</tr>';
                });
                
                html += '</table>';
                tableData.innerHTML = html;
                
                status.textContent = `表 "${tableName}" 已加载，共 ${values.length} 行数据`;
            } catch (error) {
                console.error(error);
                status.textContent = `错误: ${error.message}`;
                tableData.innerHTML = `<div class="error">无法读取表数据: ${error.message}</div>`;
            }
        }
    </script>
</body>
</html>